<?php

namespace app\admin\controller;

use support\Request;
use support\Response;
use app\model\CompanyMasterModel;
use Exception;

/**
 * 公司管理账户控制器
 */
class CompanyMasterController
{
    /**
     * 获取公司管理账户列表
     */
    public function list(Request $request): Response
    {
        try {
            $companyId = $request->get('company_id');
            if (empty($companyId)) throw new Exception('参数错误');
            $list = CompanyMasterModel::where('company_id', $companyId)->with('user')->get();
            return json(['data' => $list, 'msg' => '获取成功', 'code' => 20000]);
        } catch (Exception $e) {
            return json(['data' => null, 'msg' => $e->getMessage(), 'code' => 0]);
        }
    }

    /**
     * 添加管理账户
     */
    public function add(Request $request): Response
    {
        try {
            $companyId = $request->post('company_id');
            $userId = $request->post('user_id');
            if (empty($companyId) || empty($userId)) throw new Exception('参数错误');
            if (CompanyMasterModel::where('company_id', $companyId)->where('user_id', $userId)->exists()) {
                throw new Exception('该用户已是管理账户');
            }
            CompanyMasterModel::create([
                'company_id' => $companyId,
                'user_id' => $userId,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            return json(['data' => null, 'msg' => '添加成功', 'code' => 20000]);
        } catch (Exception $e) {
            return json(['data' => null, 'msg' => $e->getMessage(), 'code' => 0]);
        }
    }

    /**
     * 删除管理账户
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            CompanyMasterModel::where('id', $id)->delete();
            return json(['data' => null, 'msg' => '删除成功', 'code' => 20000]);
        } catch (Exception $e) {
            return json(['data' => null, 'msg' => $e->getMessage(), 'code' => 0]);
        }
    }
}
